/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package locusts.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Set;
import locusts.lib.ObjectIdFactory;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.filter.CompressionFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.handler.demux.DemuxingIoHandler;
import org.apache.mina.management.StatCollector;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

/**
 *
 * @author Hamish Morgan
 */
public class ServerNetHandler extends DemuxingIoHandler {

    //
    private final IoAcceptor acceptor;
    private final SocketAcceptorConfig saConfig;
    private final InetSocketAddress address;
    private final StatCollector stats;

    public ServerNetHandler(int port) {
        acceptor = new SocketAcceptor();
        stats = new StatCollector(acceptor, 1000);
        stats.start();
        saConfig = new SocketAcceptorConfig();
        address = new InetSocketAddress(port);
        init();

    }

    private void init() {
        ByteBuffer.setUseDirectBuffers(false);
        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

//        saConfig.getFilterChain().addLast("compression",
//                new CompressionFilter(CompressionFilter.COMPRESSION_MAX));
//        saConfig.getFilterChain().addLast("logger", new LoggingFilter());
        saConfig.getFilterChain().addLast("codec", new ProtocolCodecFilter(
                new ObjectSerializationCodecFactory()));
    }

    public StatCollector getStats() {
        return stats;
    }

    public InetSocketAddress getAddress() {
        return address;
    }

    public SocketAcceptorConfig getSaConfig() {
        return saConfig;
    }

    public IoAcceptor getAcceptor() {
        return acceptor;
    }

    public void start() throws IOException {
        acceptor.bind(address, this, saConfig);
        System.out.println("Locusts server started on " + address);
    }

    public void stop() {
        acceptor.unbindAll();
        System.out.println("Locusts server stopped.");
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        assert session.getAttribute("id") == null;
        session.setAttribute("id", ObjectIdFactory.nextIdFor(IoSession.class));
        super.sessionCreated(session);
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        super.sessionOpened(session);
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause)
            throws Exception {
        super.exceptionCaught(session, cause);
        cause.printStackTrace();
        session.close();
    }

    @Override
    public void messageSent(IoSession session, Object message) throws
            Exception {
        assert session.getAttribute("id") != null;
        super.messageSent(session, message);
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws
            Exception {
        assert session.getAttribute("id") != null;

        super.messageReceived(session, message);
    }

    public Set<IoSession> getManagedSessions() {
        return acceptor.getManagedSessions(address);
    }

    public int numManagedSessions() {
        return acceptor.getManagedSessions(address).size();
    }
    public void broadcast(Object message) {
        for (IoSession session : getManagedSessions()) {
            assert session.getAttribute("id") != null;
//            if (session.getAttribute("Player Data Sent") != null)
            session.write(message);
        }
        
    }


}
